package ink.tsg.scheduled.config;

import ink.tsg.scheduled.repository.SpringScheduledCronRepository;
import ink.tsg.scheduled.task.DynamicPrintTask;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronSequenceGenerator;
import org.springframework.scheduling.support.CronTrigger;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author tsg
 * @version 1.0
 * @description: TODO
 * @date 2022/5/19 13:35
 */
@Slf4j
@Configuration
public class ScheduledConfig implements SchedulingConfigurer {
    @Autowired
    private SpringScheduledCronRepository cronRepository;

    //注入我们的定时任务类
    @Autowired
    DynamicPrintTask task;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

        //可以通过改变数据库数据进而实现动态改变执行周期
        /**
         *
         * public void addTriggerTask(Runnable task, Trigger trigger) {
         *      this.addTriggerTask(new TriggerTask(task, trigger));
         *     }
         * 使用这个方法会增加一个触发任务 ：即  ！这个定时任务的下一次执行时间！
         * 参数：Runnable    一个事件
         * 参数：Trigger     一个触发器
         * public interface Trigger {
         *     @Nullable
         *     Date nextExecutionTime(TriggerContext var1);   下一次执行时间
         * }
         */
        taskRegistrar.addTriggerTask(((Runnable) task),
                triggerContext -> {
                    //查询数据库  获得该类的cron表达式
                    String cronExpression = cronRepository.findSpringScheduledCronByCronKey(task.getClass().getName()).getCronExpression();
//                    log.info("cronRepository.findByCronExpression():"+cronExpression);
                    System.out.println(cronExpression);
                    if(!CronSequenceGenerator.isValidExpression(cronExpression)){
                        throw new RuntimeException("表达式错误!");
                    }
                    // CronTrigger实现了Trigger
                    return new CronTrigger(cronExpression).nextExecutionTime(triggerContext);
                }
        );

    }
//    @Bean
//    public Executor taskExecutor() {
//        return Executors.newScheduledThreadPool(10);
//    }
}
